﻿using _5E.NHibernateRepository.SessionStorage;
using NHibernate;

namespace _5E.NHibernateRepository
{
    public class SessionFactory
    {
        private static ISessionFactory s_Instance = null;
        public static ISessionFactory Instance
        {
            get
            {
                if (null == s_Instance)
                    Init();

                return s_Instance;
            }
        }

        public static ISession CurrentSession
        {
            get
            {
                ISessionStorageContainer container = SessionStorageFactory.SessionStorageContainer;
                ISession currentSession = container.CurrentSession;

                if (null == currentSession)
                {
                    currentSession = Instance.OpenSession();
                    container.Store(currentSession);
                }
                return currentSession;
            }
        }

        private static string s_ConfigFilePath = null;
        public static string ConfigFilePath { set { s_ConfigFilePath = value; } }

        public static void Init()
        {
            NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();

            config.Configure(s_ConfigFilePath);

            s_Instance = config.BuildSessionFactory();
        }
    }
}
